package com.gatherlife.manager.controller;


import java.net.URLDecoder;
import java.net.URLEncoder;

import javax.servlet.http.Cookie;

import org.apache.log4j.Logger;
import org.xson.common.object.XCO;
import org.xson.tangyuan.cache.CacheComponent;
import org.xson.tangyuan.cache.TangYuanCache;
import org.xson.tangyuan.executor.ServiceActuator;
import org.xson.tangyuan.web.RequestContext;

import com.gatherlife.manager.Constant;
import com.gatherlife.manager.utils.CookieUtil;
import com.gatherlife.manager.utils.CryptoUtil;
import com.gatherlife.manager.utils.DESUtil;
import com.gatherlife.manager.utils.MD5Util;
import com.gatherlife.manager.utils.XCOUtil;

public class LoginController {

	static Logger log = Logger.getLogger(LoginController.class);
	
	
	/**
	 * 获取专家用户信息
	 */
	private XCO getSystemUser(XCO xco) {
		XCO request = new XCO();
		request.setStringValue("user_name", xco.getStringValue("user_name"));
		
		XCO result = ServiceActuator.execute("user/getUserInfo", request);
		if (null == result || !result.exists("user_id")) {
			return XCOUtil.getResult(11, "用户名密码错误");
		}
		System.out.println(xco.toXMLString());
		String pwd1 = xco.getStringValue("password");
		String pwd2 = result.getStringValue("password");

		if (CryptoUtil.isValid(pwd1, pwd2)) {
			return result;
		}else{
			return XCOUtil.getResult(11, "用户名密码错误");
		}

	}
	

	public void userLogin(RequestContext context) throws Exception{
		
		TangYuanCache redis = CacheComponent.getInstance().getCache("cache1");

		XCO arg = (XCO) context.getArg();

		// 1. 验证码
		String img_vcode = arg.getStringValue("verifyCode");
		String rediskey = (String)redis.get(arg.getStringValue("verifyKey"));
		if (!img_vcode.equals(rediskey)) {
			context.setResult(XCOUtil.getResult(11, "验证码错误"));
			return;
		}
		redis.remove(rediskey);

		// 2. 访问数据库
		XCO user = getSystemUser(arg);

		// 3. check user
		if (null == user || !user.exists("user_id")) {
			 context.setResult(XCOUtil.getResult(12, "用户名密码错误"));
			 return;
		}
		
		// 3. 判断用户是否停用
		if (null != user && user.getIntegerValue("state") == 0) {
			 context.setResult(XCOUtil.getResult(13, "该用户已经被停用"));
			 return;
		}
		
		// 4. 组装数据
		XCO tokenUser = new XCO();
		tokenUser.setLongValue("user_id", user.getLongValue("user_id"));
		tokenUser.setStringValue("user_name", user.getStringValue("user_name"));
		tokenUser.setStringValue("real_name", user.getStringValue("real_name"));
		tokenUser.setLongValue("role_id", user.getLongValue("role_id"));
		// 5. 合成token
		String token = DESUtil.encrypt(MD5Util.MD5(tokenUser.toXMLString() + System.nanoTime()), Constant.DES_KEY);
		
		// 6. 放入redis
		redis.put(Constant.SYSTEM_USER_TOKEN_PREFIX + token, tokenUser.toXMLString(), Constant.REDIS_COOKIE_TOKEN_EXPIRE);
		
		// 7. 处理Cookie
		CookieUtil.clearAllCookies(context.getRequest(), context.getResponse(), Constant.SYSTEM_COOKIE_NAME_TOKEN, Constant.SYS_DOMAIN);
		Cookie tokenCookie = new Cookie(Constant.SYSTEM_COOKIE_NAME_TOKEN, URLEncoder.encode(token, "utf-8"));
		tokenCookie.setDomain(Constant.SYS_DOMAIN);
		tokenCookie.setPath(Constant.COOKIE_PATH);
		tokenCookie.setMaxAge(Constant.COOKIE_MAXAGE);
		context.getResponse().addCookie(tokenCookie);
		
		XCO result = new XCO();
		result.setLongValue("role_id", user.getLongValue("role_id"));
		// 8. 设置Result
		context.setResult(XCOUtil.getResult(0, result));
	}
	
	/**
	 * 用户退出
	 * @param context
	 * @throws Exception
	 */
	public void userexit(RequestContext context) throws Exception {
		String token = CookieUtil.getToken(context.getRequest(), Constant.SYSTEM_COOKIE_NAME_TOKEN);
		if (null == token) {
			return;
		}
		token = URLDecoder.decode(token, "utf-8");

		// TODO: 需要判断用户ID

		TangYuanCache redis = CacheComponent.getInstance().getCache("cache1");
		redis.remove(Constant.SYSTEM_COOKIE_NAME_TOKEN + token);

		// 清除cookie值
		String domain = Constant.USER_DOMAIN;
		CookieUtil.clearAllCookies(context.getRequest(), context.getResponse(), Constant.SYSTEM_COOKIE_NAME_TOKEN, domain);

		context.setResult(XCOUtil.getResult(0));
	}
	
	public void addSystemUser(RequestContext requestContext) {
		//查询当前用户的密码 
		XCO xco = (XCO) requestContext.getArg();
		
		
		String pwd = xco.getStringValue("password");
		xco.setStringValue("password", CryptoUtil.encryption(pwd));
		
		XCO req = ServiceActuator.execute("user/addUser", xco);
		if(req.getLongValue("user_id")!=0){
			requestContext.setResult(XCOUtil.getResult(0, "用户添加成功"));
		}else{
			requestContext.setResult(req);
		}
	}
	
	public void updateUser(RequestContext requestContext) {
		//查询当前用户的密码 
		XCO xco = (XCO) requestContext.getArg();
		
		
		String pwd = xco.getStringValue("password");
		xco.setStringValue("password", CryptoUtil.encryption(pwd));
		
		XCO req = ServiceActuator.execute("user/updateUser", xco);
		if(req.getIntegerValue("nCount") > 0){
			requestContext.setResult(XCOUtil.getResult(0, "密码修改成功"));
		}else{
			requestContext.setResult(XCOUtil.getResult(12, "密码修改失败"));
		}
	}
	
	public void updateSysPwd(RequestContext requestContext) {
		//查询当前用户的密码 
		XCO xco = (XCO) requestContext.getArg();
		XCO result = ServiceActuator.execute("user/getUserInfo22", xco);
		
		XCO returnXCO = new XCO();
		
		String newPwd = xco.getStringValue("password");
		xco.setStringValue("password", CryptoUtil.encryption(newPwd));
		
		String pwd1 = xco.getStringValue("oldPwd");
		String pwd2 = result.getStringValue("password");

		if (!CryptoUtil.isValid(pwd1, pwd2)) {
			returnXCO = XCOUtil.getResult(11, "原密码错误");
		}else{
			XCO req = ServiceActuator.execute("user/updateUser2", xco);
			if(req.getIntegerValue("nCount") > 0){
				returnXCO = XCOUtil.getResult(0, "密码修改成功");
			}else{
				returnXCO = XCOUtil.getResult(12, "密码修改失败");
			}
		}
		requestContext.setResult(returnXCO);
	}

}
